<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>蓝牙服务扫描器</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px 5px;
        }
        .btn:hover {
            background: #0056b3;
        }
        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
            border-left: 4px solid #007bff;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            border-left-color: #dc3545;
        }
        .success {
            background: #d4edda;
            color: #155724;
            border-left-color: #28a745;
        }
        .device-info {
            margin: 15px 0;
            padding: 15px;
            background: #e9ecef;
            border-radius: 5px;
        }
        .service-info {
            margin: 10px 0;
            padding: 10px;
            background: #fff3cd;
            border-radius: 3px;
        }
        .characteristic-info {
            margin: 5px 0;
            padding: 8px;
            background: #cce5ff;
            border-radius: 3px;
            margin-left: 20px;
        }
        .uuid {
            font-family: 'Consolas', monospace;
            background: #f1f3f4;
            padding: 2px 4px;
            border-radius: 3px;
            color: #d63384;
            font-weight: bold;
        }
        .properties {
            font-size: 12px;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 蓝牙服务扫描器</h1>
        <p>此工具可以帮助您发现按摩椅设备的蓝牙服务UUID和特征UUID</p>
        
        <div>
            <button class="btn" onclick="scanAllDevices()">扫描所有蓝牙设备</button>
            <button class="btn" onclick="scanMassageChair()">扫描按摩椅设备</button>
            <button class="btn" onclick="clearResults()">清除结果</button>
        </div>

        <div id="results"></div>
    </div>

    <script>
        let currentDevice = null;

        function addResult(message, type = '') {
            const results = document.getElementById('results');
            const div = document.createElement('div');
            div.className = `result ${type}`;
            div.innerHTML = message;
            results.appendChild(div);
        }

        function clearResults() {
            document.getElementById('results').innerHTML = '';
        }

        async function scanAllDevices() {
            try {
                addResult('🔍 开始扫描所有蓝牙设备...', 'success');
                
                const device = await navigator.bluetooth.requestDevice({
                    acceptAllDevices: true,
                    optionalServices: ['battery_service', 'device_information']
                });

                await analyzeDevice(device);
            } catch (error) {
                addResult(`❌ 扫描失败: ${error.message}`, 'error');
            }
        }

        async function scanMassageChair() {
            try {
                addResult('🪑 开始扫描按摩椅设备...', 'success');
                
                const device = await navigator.bluetooth.requestDevice({
                    filters: [
                        { namePrefix: '按摩椅' },
                        { namePrefix: 'MassageChair' },
                        { namePrefix: 'MASSAGE' },
                        { namePrefix: 'Chair' },
                        { namePrefix: 'Relax' }
                    ],
                    optionalServices: [
                        0xFFF0, 0xFFF1, 0xFFF2, 0xFFF3, 0xFFF4, 0xFFF5,
                        '12345678-1234-1234-1234-123456789abc',
                        'generic_access', 'generic_attribute', 'device_information'
                    ]
                });

                await analyzeDevice(device);
            } catch (error) {
                if (error.name === 'NotFoundError') {
                    addResult('ℹ️ 用户取消了设备选择', '');
                } else {
                    addResult(`❌ 扫描失败: ${error.message}`, 'error');
                }
            }
        }

        async function analyzeDevice(device) {
            try {
                currentDevice = device;
                
                let deviceHtml = `
                    <div class="device-info">
                        <h3>📱 设备信息</h3>
                        <p><strong>名称:</strong> ${device.name || '未知设备'}</p>
                        <p><strong>ID:</strong> ${device.id}</p>
                        <p><strong>状态:</strong> ${device.gatt.connected ? '已连接' : '未连接'}</p>
                    </div>
                `;

                addResult(deviceHtml);
                addResult('🔗 正在连接设备...', '');

                const server = await device.gatt.connect();
                addResult('✅ 设备连接成功，正在获取服务...', 'success');

                const services = await server.getPrimaryServices();
                addResult(`🔧 发现 ${services.length} 个服务`, 'success');

                for (const service of services) {
                    let serviceHtml = `
                        <div class="service-info">
                            <h4>🛠️ 服务</h4>
                            <p><strong>UUID:</strong> <span class="uuid">${service.uuid}</span></p>
                            <p><strong>是否主服务:</strong> ${service.isPrimary ? '是' : '否'}</p>
                        </div>
                    `;

                    try {
                        const characteristics = await service.getCharacteristics();
                        if (characteristics.length > 0) {
                            serviceHtml += `<p><strong>特征数量:</strong> ${characteristics.length}</p>`;
                            
                            for (const characteristic of characteristics) {
                                const properties = [];
                                if (characteristic.properties.read) properties.push('读取');
                                if (characteristic.properties.write) properties.push('写入');
                                if (characteristic.properties.writeWithoutResponse) properties.push('无响应写入');
                                if (characteristic.properties.notify) properties.push('通知');
                                if (characteristic.properties.indicate) properties.push('指示');

                                serviceHtml += `
                                    <div class="characteristic-info">
                                        <p><strong>🔌 特征UUID:</strong> <span class="uuid">${characteristic.uuid}</span></p>
                                        <p class="properties"><strong>支持操作:</strong> ${properties.join(', ') || '无'}</p>
                                    </div>
                                `;
                            }
                        }
                    } catch (e) {
                        serviceHtml += `<p style="color: red;">获取特征失败: ${e.message}</p>`;
                    }

                    addResult(serviceHtml);
                }

                // 生成代码建议
                if (services.length > 0) {
                    let codeHtml = `
                        <div class="result success">
                            <h4>💡 代码配置建议</h4>
                            <p>根据扫描结果，您可以在代码中使用以下UUID:</p>
                            <pre style="background: #f8f9fa; padding: 10px; border-radius: 5px; overflow-x: auto;">
// 在 src/renderer/bluetooth.js 中修改以下配置:

// 主要服务UUID (选择一个最可能的服务)
this.MASSAGE_CHAIR_SERVICE_UUID = '${services[0].uuid}';

// 特征UUID (需要根据实际测试选择支持写入的特征)
this.MASSAGE_CHAIR_CHARACTERISTIC_UUID = '获取特征后填入';
                            </pre>
                            <p><strong>⚠️ 注意:</strong> 请选择支持"写入"或"无响应写入"的特征用于发送控制指令</p>
                        </div>
                    `;
                    addResult(codeHtml);
                }

            } catch (error) {
                addResult(`❌ 设备分析失败: ${error.message}`, 'error');
            }
        }

        // 检查浏览器支持
        if (!navigator.bluetooth) {
            addResult('❌ 您的浏览器不支持Web Bluetooth API', 'error');
        } else {
            addResult('✅ 浏览器支持Web Bluetooth API', 'success');
        }
    </script>
</body>
</html>